'''
author:        Wang Chenyang <cy-wang21@mails.tsinghua.edu.cn>
date:          2025-08-06 22:37:14
Copyright © Department of Physics, Tsinghua University. All rights reserved
'''

from flask import Flask, jsonify, render_template_string, request
from flask_cors import CORS
from item_viewer import LiteratureViewer

app = Flask(__name__)
CORS(app)

viewer = LiteratureViewer()

@app.route("/api/load_file", methods=['POST'])
def load_file():
    data = request.get_json()
    file_path = data.get('file_path', "")
    try:
        viewer.load_from_file(file_path)
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})
    return jsonify({'success': True, 'all_articles': viewer.literature_list, 'info': viewer.get_all()})


@app.route("/api/sort_by", methods=['POST'])
def sort_by():
    data = request.get_json()
    sort_by = data.get('sort_by', "")
    reverse = data.get('reverse', False)
    viewer.sort_by(sort_by, reverse)
    return jsonify({
        'success': True,
        'info': viewer.get_all()
    })


@app.route("/api/select_keywords", methods=['POST'])
def select_keywords():
    data = request.get_json()
    keywords = data.get('keywords', "")
    viewer.select_kw(keywords)

    return jsonify({
        'success': True,
        'info': viewer.get_all()
    })


@app.route("/api/deselect_keywords", methods=['POST'])
def deselect_keywords():
    data = request.get_json()
    keywords = data.get('keywords', "")
    viewer.deselect_kw(keywords)
    return jsonify({
        'success': True,
        'info': viewer.get_all()
    })

@app.route("/api/hide_article", methods=['POST'])
def hide_article():
    data = request.get_json()
    article_index = data.get('article_index')
    viewer.hide_item(article_index)
    return jsonify({
        'success': True,
        'info': viewer.get_all()
    })

# Implement in the front-end
# @app.route("/api/get_article_detail", methods=['POST'])
# def get_article_detail():
#     data = request.get_json()
#     article_index = data.get('article_index')
    
#     if article_index is not None and 0 <= article_index < len(viewer.literature_list):
#         item = viewer.literature_list[article_index]
#         return jsonify({
#             'success': True,
#             'article': {
#                 'index': article_index,
#                 'date': item['date'],
#                 'title': item['title'],
#                 'author': item['author'],
#                 'score': item.get('score', 'N/A'),
#                 'publication': item.get('publication', 'N/A'),
#                 'abstract': item.get('abstract', ''),
#                 'keywords': item.get('keywords', []),
#                 'note': item.get('note', '')
#             }
#         })
#     else:
#         return jsonify({'success': False, 'error': '无效的文章索引'})

@app.route('/')
def index():
    return render_template_string(open('new_index.html', 'r', encoding='utf-8').read())

@app.route('/style.css')
def style():
    return open('new_style.css', 'r', encoding='utf-8').read(), 200, {'Content-Type': 'text/css'}

@app.route('/script.js')
def script():
    return open('new_script.js', 'r', encoding='utf-8').read(), 200, {'Content-Type': 'application/javascript'}

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
